/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 * SdProjectController
 * SD项目立项
 * 修改纪录
 * 2021-11-22 版本：1.0 jiangtao 创建。
 *
 * @version 版本：1.0
 * @author 作者：jiangtao
 * 创建日期：2021-11-22
 */
package com.topscomm.gpm.controller;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.CboSystemConst;
import com.topscomm.cbo.pojo.*;
import com.topscomm.cbo.service.ICboApprovalNodeInsService;
import com.topscomm.cbo.service.ICboDeptService;
import com.topscomm.cbo.service.ICboItemDetailsService;
import com.topscomm.cbo.service.ICboUserService;
import com.topscomm.cbo.service.impl.CboDeptService;
import com.topscomm.cbo.service.impl.CboUserGroupService;
import com.topscomm.gpm.controller.auto.GpmProjectControllerAuto;
import com.topscomm.ltc.pojo.LtcContractApplyEntity;
import com.topscomm.ltc.service.ILtcChanceBackboneService;
import com.topscomm.ltc.service.ILtcContractApplyService;
import com.topscomm.main.hessian.IMpmProjectService;
import com.topscomm.mms.pojo.MmsDeptExtraInfoEntity;
import com.topscomm.mms.service.IMmsDeptExtraInfoService;
import com.topscomm.mmsltc.pojo.LtcBidApplyEntity;
import com.topscomm.mmsltc.service.ILtcBidApplyService;
import com.topscomm.pub.util.*;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.gpm.GpmSystemConst;
import com.topscomm.gpm.pojo.*;
import com.topscomm.gpm.service.impl.*;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.common.DatacodeCache;
import com.topscomm.tap.common.ParameterCache;
import com.topscomm.tap.common.SessionUserBean;
import com.topscomm.tap.common.TapSystemConst;
import com.topscomm.tap.security.SecurityUserDetails;
import com.topscomm.tap.threadlocal.ThreadLocalContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.pub.vo.ResponseResult;

/**
 * @author: jiangtao
 * @date: 2021-11-22
 * @description:SD项目立项Controller
 * @modify:
 */
@RestController
@RequestMapping("sd/project")
public class GpmProjectController extends GpmProjectControllerAuto implements IGpmProjectController {
	@Autowired
	private ILtcContractApplyService contractApplyService;
	@Autowired
	private ILtcBidApplyService ltcBidApplyService;
	@Autowired
	private ILtcChanceBackboneService chanceBackboneService;
	@Autowired
	private CboUserGroupService cboUserGroupService;
	@Autowired
	private ICboDeptService cboDeptService;
	@Autowired
	private ICboUserService cboUserService;
	@Autowired
	private ICboApprovalNodeInsService cboApprovalNodeInsService;
	@Autowired
	private GpmWfFormService gpmWfFormService;
	@Autowired
	private GpmProjectSuperviseService gpmProjectSuperviseService;
	@Autowired
	private IMmsDeptExtraInfoService mmsDeptExtraInfoService;
	@Autowired
	private GpmProjectAppointmentService gpmProjectAppointmentService;
	@Autowired
	private GpmProjectPlanService gpmProjectPlanService;
	@Autowired
	private GpmProjectReviewService gpmProjectReviewService;
	@Autowired
	private IMpmProjectService mpmProjectService;
	@Autowired
	private GpmProjectResourcePoolService gpmProjectResourcePoolService;
	@Autowired
	private ICboItemDetailsService cboItemDetailsService;
	@Autowired
	@Qualifier("securityUserDetailsService")
	private UserDetailsService userDetailsService;

	/**
	 * @param paraMap
	 * @return
	 * @author: jiangtao
	 * @date: 2021-11-22
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		//
		if(paraMap.containsKey("qry_whetherhistorydata")) {
			String value = ConvertUtil.convertToString(paraMap.get("qry_whetherhistorydata"));
			if(!StringUtil.isEmpty(value)) {
				if("0".equals(value)) {
					sql.appendSingle(" and whetherhistorydata is null");
				} else {
					sql.appendSingle(" and whetherhistorydata = {0}", value);
				}
			}
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state={0}", value);
		}
		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_begindocdate")) {
			String value = paraMap.get("qry_begindocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_deptname")) {
			String value = paraMap.get("qry_deptname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
		}

		if (paraMap.containsKey("qry_deptcode")) {
			String value = paraMap.get("qry_deptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and deptcode like '{0}%'", value);
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state={0}", value);
		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0}", value);
		}

		// 自己添加的条件
		if (paraMap.containsKey("qry_projectmanager")) {
			String value = paraMap.get("qry_projectmanager").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (projectmanager like '%{0}%' or projectmanagercode like '%{0}%') ", value);
		}
		if (paraMap.containsKey("qry_projectname")) {
			String value = paraMap.get("qry_projectname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectname like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_user")) {
			String value = paraMap.get("qry_user").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (username like '%{0}%' or usercode like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_project")) {
			String value = paraMap.get("qry_project").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (projectname like '%{0}%' or projectnumber like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_projectnumber")) {
			String value = paraMap.get("qry_projectnumber").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectnumber like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0}", value);
		}
		if (paraMap.containsKey("qry_projectstate")) {
			String value = ConvertUtil.convertToString(paraMap.get("qry_projectstate"));
			if (!StringUtil.isEmpty(value)) {
				if (!value.contains(GpmSystemConst.SdProjectState.ProjectOngoing)) {
					sql.appendSingle(" and projectstate in ({0})", value);
				} else {
					sql.appendSingle(" and projectstate in ({0},{1})", GpmSystemConst.ProjectOngoingState, value);
				}
			}
		}
		if (paraMap.containsKey("qry_projectlevel")) {
			String value = paraMap.get("qry_projectlevel").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and projectlevel in ({0})", value);
			}
		}
		if (paraMap.containsKey("qry_open")) {
			String value = paraMap.get("qry_open").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and open = '{0}'", value);
			}
		}
		if (paraMap.containsKey("qry_projectid")) {
			String value = paraMap.get("qry_projectid").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and id = '{0}'", value);
			}
		}
        if (paraMap.containsKey("qry_bidcycle")) {
            String value = paraMap.get("qry_bidcycle").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and bidcycle = '{0}'", value);
            }
        }
		if (paraMap.containsKey("qry_sourcetype")) {
			String value = paraMap.get("qry_sourcetype").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and sourcetype in ({0})", value);
			}
		}
		if (paraMap.containsKey("qry_sponsor")) {
			String value = paraMap.get("qry_sponsor").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and (sponsor like '%{0}%' or sponsorcode like '%{0}%')", value);
			}
		}
		if (paraMap.containsKey("qry_owner")) {
			String value = paraMap.get("qry_owner").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and (owner like '%{0}%' or ownercode like '%{0}%')", value);
			}
		}
		if (paraMap.containsKey("qry_createdepart")) {
			String value = paraMap.get("qry_createdepart").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and deptcommoncode1 in ({0})", value);
			}
		}
		if (paraMap.containsKey("qry_contractcode")) {
			String value = paraMap.get("qry_contractcode").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and instr(','|| contractcode ||',','{0}' )>0 ",value);
			}
		}
		if (paraMap.containsKey("startDateForFinisthDate")) {
			String value = ConvertUtil.convertToString(paraMap.get("startDateForFinisthDate"));
			sql.appendSingle(" and finishDate > {0}", SQLAdapter.toDateShort(value));
		}
		if (paraMap.containsKey("endDaterFinisthDate")) {
			String value = ConvertUtil.convertToString(paraMap.get("endDaterFinisthDate"));
			sql.appendSingle("  and finishDate < {0}", SQLAdapter.toDateShort(value));
		}
		if (paraMap.containsKey("startDateForActualEndDate")) {
			String value = ConvertUtil.convertToString(paraMap.get("startDateForActualEndDate"));
			sql.appendSingle("  and actualenddate > {0}", SQLAdapter.toDateShort(value));
		}
		if (paraMap.containsKey("endDateForActualEndDate")) {
			String value = ConvertUtil.convertToString(paraMap.get("endDateForActualEndDate"));
			sql.appendSingle(" and actualenddate < {0}", SQLAdapter.toDateShort(value));
		}
		// 项目异常状态查询条件
		if (paraMap.containsKey("qry_abnormalstate")) {
			String value = ConvertUtil.convertToString(paraMap.get("qry_abnormalstate"));
			sql.appendSingle(" and abnormalstate in ({0}) ", value);
		}
		if (paraMap.containsKey("qry_supervisestate")) {
			String value = paraMap.get("qry_supervisestate").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle("and (");
				// 若有选择无督办筛选条件则先执行（3为无督办对应编号）
				if (value.contains("3")) {
					sql.appendSingle("(NOT EXISTS (SELECT id FROM GPMProjectSupervise supervise WHERE" +
							" supervise.projectid = GPMPROJECT.id))");
					// 对字符串进行截取
					if (value.length() > 1) {
						sql.appendSingle(" or ");
						// 因为字符串排列顺序不同，若无督办情况不是第一个选中的选项则进行第一种截取（例如"0,1,3", "2,3,1"等情况）
						// 若第一个选中的是无督办情况则进行第二种截取。主要区别在于逗号的位置不同。（例如"3,1,0"等情况）
						if (value.indexOf("3") != 0) {
							value = value.replace(",3", "");
						} else {
							value = value.replace("3,", "");
						}
					}
				}
				// 筛选进行中、超期、已完成三个状态的督办情况
				if (!value.contains("3")) {
					sql.appendSingle("(EXISTS (SELECT id FROM GPMProjectSupervise supervise WHERE" +
							" supervise.projectid = GPMPROJECT.id AND supervise.supervisestate in ({0})))", value);
				}
				sql.appendSingle(")");
			}
		}
		// 项目监管页筛选条件
		if (paraMap.containsKey("qry_finishproject")) {
			String value = paraMap.get("qry_finishproject").toString();
			if (!StringUtil.isEmpty(value) && "0".equals(value)) {
				String projectstate = GpmSystemConst.SdProjectState.ProjectApproval + "," + GpmSystemConst.SdProjectState.ProjectUnApprovaled + "," + GpmSystemConst.ProjectOngoingState;
				sql.appendSingle(" and {0} in ({1}) ", SQLAdapter.isNull(GpmProjectEntity.FieldProjectstate, "0"), projectstate);
			}
		}
		// 项目状态大类筛选
		if (paraMap.containsKey("qry_projectlargestate")) {
			String value = paraMap.get("qry_projectlargestate").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and ( 1!=1 ");
				if (value.contains("0")) {
					sql.appendSingle(" or (projectmanagercode = '{0}' and {1} in ({2}))", this.getUserBean().getUser().getCode(),
							SQLAdapter.isNull("projectstate", "0"), GpmSystemConst.SdProjectState.ProjectApproval + "," + GpmSystemConst.SdProjectState.ProjectUnApprovaled);
				}
				if (value.contains("1")) {
					sql.appendSingle(" or projectstate in ({0}) ", GpmSystemConst.ProjectOngoingState);
				}
				if (value.contains("2")) {
					sql.appendSingle(" or projectstate in ({0}) ", GpmSystemConst.SdProjectState.ProjectNormalEnd + "," + GpmSystemConst.SdProjectState.ProjectUnNormalEnd);
				}
				sql.appendSingle(" ) ");
			}
		}
		// 数据权限控制，如果是交付案例库或者是系统超管,不控制数据权限
		if (!paraMap.containsKey("qry_open") && this.getUserBean().getUser().getAdminlevel() < 1) {
			String value = getUserBean().getUser().getCode();
			// 作为项目经理
			sql.appendSingle(" and ((projectmanagercode = '{0}') ", value);
			// 部门拓展信息表权限查询拼接
			MmsDeptExtraSearchSql(sql, paraMap);
			// 省区地市表权限查询拼接
			MmsProvinceMatchSearchSql(sql, paraMap);
			// 数据权限
			String dataPermission = this.service.getDataPermission(TapSystemConst.TapOperationTypeEnum.Select, "", getUserBean());
			if (!dataPermission.isEmpty()) {
				sql.appendSingle(" or ({0}) ", dataPermission);
			}
			// 相关方
			sql.appendSingle(" or (EXISTS (SELECT  DISTINCT PROJECTCODE FROM GPMPROJECTSTAKEHOLDER STACKHOLDER WHERE STACKHOLDER.USERCODE = '{0}' AND STACKHOLDER.ENABLED = 1 AND STACKHOLDER.PROJECTCODE=GPMPROJECT.PROJECTCODE )) ", getUserBean().getUser().getCode());
			sql.appendSingle(") ");
		}
		if (paraMap.containsKey("qry_dataPermission")) {
			String value = ConvertUtil.convertToString(paraMap.get("qry_dataPermission"));
			if ("inChargeMe".equals(value)) {
				// 我负责的（项目经理是我）
				sql.appendSingle(" and PROJECTMANAGERCODE='{0}' ", this.getUserBean().getUser().getCode());
			} else if ("participate".equals(value)) {
				// 我参与的（项目组成员中有我）
				sql.appendSingle(" and EXISTS (SELECT PROJECTCODE FROM GPMPROJECTTEAM WHERE GPMPROJECT.PROJECTCODE = GPMPROJECTTEAM.PROJECTCODE AND GPMPROJECTTEAM.USERCODE = '{0}' AND GPMPROJECTTEAM.STATE = 9  AND GPMPROJECTTEAM.ENABLED = 1) ", this.getUserBean().getUser().getCode());
			}
		}

		return sql.toString();
	}


	protected String spellContractRefListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" contractstate = 1 and contractcode is not null and signapprovalstate = 9");
		// 查询项目经理所属省区的所有合同
		if (paraMap.containsKey("qry_deptcommoncode1")) {
			String value =ConvertUtil.convertToString(paraMap.get("qry_deptcommoncode1"));
			if(!StringUtil.isEmpty(value)) {
				String deptCommonCode = mmsDeptExtraInfoService.getDeptCommonCode(value);
				sql.appendSingle(" and (deptcommoncode1 like '{0}' or exists ( select 1 from {1} where {1}.levelcode = deptname1 and {1}.deptcommoncode like '{0}'))", deptCommonCode,"MmsProvinceCityMatchinfo");
			} else {
				String deptCommonCode = mmsDeptExtraInfoService.getDeptCommonCode(this.getUserBean().getDept().getCode());
				sql.appendSingle(" and (deptcommoncode1 like '{0}' or exists ( select 1 from {1} where {1}.levelcode = deptname1 and {1}.deptcommoncode like '{0}'))", deptCommonCode,"MmsProvinceCityMatchinfo");
			}
		} else {
			String deptCommonCode = mmsDeptExtraInfoService.getDeptCommonCode(this.getUserBean().getDept().getCode());
			sql.appendSingle(" and (deptcommoncode1 like '{0}' or exists ( select 1 from {1} where {1}.levelcode = deptname1 and {1}.deptcommoncode like '{0}'))", deptCommonCode,"MmsProvinceCityMatchinfo");
		}

		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_user")) {
			String value = paraMap.get("qry_user").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (username like '%{0}%' or usercode like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_deptcode")) {
			String value = paraMap.get("qry_deptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and deptcode like '{0}%'", value);
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state={0}", value);
		}
		if (paraMap.containsKey("qry_contractcode")) {
			String value = paraMap.get("qry_contractcode").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and contractcode like '%{0}%' ",value);
			}
		}
		if (paraMap.containsKey("qry_contractname")) {
			String value = paraMap.get("qry_contractname").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and contractname like '%{0}%' ",value);
			}
		}
		return sql.toString();
	}


	/**
	 * @Description: 返回所在一级部门的机会点信息
	 * @Author: hudeyong
	 * @Date: 2021/11/17
	 * @Version: 1.0
	 */
	@GetMapping(value = "/queryChanceInfo")
	public ResponseResult<Object> queryChanceInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			StringBufferProxy sql = new StringBufferProxy();
			String deptCommonCode1 = mmsDeptExtraInfoService.getDeptCommonCode(ConvertUtil.convertToString(paraMap.get("deptcode")));
			sql.appendSingle("itemid in (select id from {0} where code = '{1}')", CboItemsEntity.tableName,"LtcDeptDifferenceGrid");
			List<Map<String,Object>> tempCodeList = cboItemDetailsService.queryMapByWhere(sql.toString());
			String tempcode = "";
			for(Map<String,Object> temp:tempCodeList) {
				String code = ","+ConvertUtil.convertToString(temp.get("code"))+",";
				if(code.indexOf((","+deptCommonCode1+","))!=-1) {
					tempcode = ConvertUtil.convertToString(temp.get("name"));
					break;
				}
			}
			sql.clear();
			if(StringUtil.isEmpty(tempcode)) {
				sql.appendSingle("deptcommoncode1 in ('{0}') and code is not null and currentphase != '7'",deptCommonCode1);
			} else {
				sql.appendSingle("deptcommoncode1 in ('{0}','{1}') and code is not null and currentphase != '7'",deptCommonCode1,tempcode);
			}
			if(paraMap.containsKey("qry_username")) {
				sql.appendSingle(" and gardenername like '%{0}%'", ConvertUtil.convertToString(paraMap.get("qry_username")));
			}
			if(paraMap.containsKey("qry_code")) {
				sql.appendSingle(" and code like '%{0}%'", ConvertUtil.convertToString(paraMap.get("qry_code")));
			}
			if(paraMap.containsKey("qry_clientname")) {
				sql.appendSingle(" and clientname like '%{0}%'", ConvertUtil.convertToString(paraMap.get("qry_clientname")));
			}
			int totalCount = chanceBackboneService.getCount(sql.toString());
			List<Map<String, Object>> tempList = new ArrayList<>();
			String sqlWhere = sql.toString();
			if (query.getPageSize() > 0) {
				tempList = chanceBackboneService.queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord(), "queryMapForPageNoClob");
			} else
				tempList = chanceBackboneService.queryMapByWhere(sqlWhere,"queryMapByWhereNoClob");
			for(Map<String, Object> map : tempList) {
				map.put("dispcurrentphase", datacodeCache.getValueDynamic("LtcChancePhase", ConvertUtil.convertToString(map.get("currentphase")), "code", "name"));
			}
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	/**
	 * @Description: 返回所在一级部门的销售项目信息
	 * @Author: hudeyong
	 * @Date: 2021/11/17
	 * @Version: 1.0
	 */
	@GetMapping(value = "/queryMpmInfo")
	public ResponseResult<Object> queryMpmInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			StringBufferProxy sql = new StringBufferProxy();
			String deptCommonCode1 = mmsDeptExtraInfoService.getDeptCommonCode(ConvertUtil.convertToString(paraMap.get("deptcode")));
			sql.appendSingle("deptcommoncode in ('{0}') and state = '9'",deptCommonCode1);
			if(paraMap.containsKey("qry_projectcode")) {
				sql.appendSingle(" and projectcode like '%{0}%'", ConvertUtil.convertToString(paraMap.get("qry_projectcode")));
			}
			if(paraMap.containsKey("qry_projectname")) {
				sql.appendSingle(" and projectname like '%{0}%'", ConvertUtil.convertToString(paraMap.get("qry_projectname")));
			}
			if(paraMap.containsKey("qry_projectmanager")) {
				sql.appendSingle(" and projectmanager like '%{0}%'", ConvertUtil.convertToString(paraMap.get("qry_projectmanager")));
			}
			Page page = mpmProjectService.queryMpmProjectByDeptcommonCode(sql.toString(),query);
			return ResponseResult.ok(page);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	/**kz
	 * @param paraMap
	 * @return
	 * @author: jiangtao
	 * @date: 2021-11-22
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/***
	 * @description: 合同参照拼接
	 * @param paraMap
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/11/23 10:02
	 * @modify:
	 */

	@GetMapping(value = "/contractRefList")
	public ResponseResult<Object> contractRefList(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = this.spellContractRefListSql(paraMap);
			int totalCount = contractApplyService.getCount(sqlWhere);
			List<Map<String, Object>> tempList = null;
			if (query.getPageSize() > 0) {
				tempList = contractApplyService.queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord(), "queryMapForPageNoClob");
			} else {
				tempList = contractApplyService.queryMapByWhere(sqlWhere, "queryMapByWhereNoClob");
			}
			List<LtcBidApplyEntity> bidApplyEntities = new ArrayList<>();
			Map<String, String> bidMap = new HashMap<>();
			// 获取对应的投标编号
			String bidcodes = tempList.stream().filter(s -> GpmSystemConst.ContractNegotiationSource.Bid.equals(ConvertUtil.convertToString(s.get("contractnsource"))))
					.map(s -> ConvertUtil.convertToString(s.get(""))).collect(Collectors.joining(",", "'", "'"));
			if(!"''".equals(bidcodes)) {
				bidApplyEntities = ltcBidApplyService.queryByWhere(" project_code in (" + bidcodes + ")");
				if(bidApplyEntities.size()>0) {
					bidMap = bidApplyEntities.stream().collect(Collectors.toMap(LtcBidApplyEntity::getProject_code, LtcBidApplyEntity::getChance_code));
				}
			}
			// 当机会点来源为投标时，需要将机会点编号赋值
			for (Map<String, Object> temp : tempList) {
				if(bidApplyEntities.size()>0) {
					String contractnsource = ConvertUtil.convertToString(temp.get("contractnsource"));
					if (GpmSystemConst.ContractNegotiationSource.Bid.equals(contractnsource)) {
						String bidcode = ConvertUtil.convertToString(temp.get("bidcode"));
						temp.put("chancecode", bidMap.get(bidcode));
					}
				}
				// 判断合同是否包含外包
				String contractCategory = ConvertUtil.convertToString(temp.get("category"));
				if("B".equals(contractCategory)) {
					temp.put("ourcontractable","1");
				} else {
					temp.put("ourcontractable","0");
				}
			}

			this.setContractDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception var7) {
			return this.handleControllerException(var7);
		}
	}



	/**
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @description: 提交审批前
	 * @author: jiangtao
	 * @date: 2021-11-22
	 * @modify:
	 */
	@Override
	protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeSubmit(dataMap, paraMap);
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交GPM项目立项申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
		dataMap.put("maintitle", mailtitle.toString());
	}

	/***
	 * @description: 新增和保存功能
	 * @param map
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/11/24 15:32
	 * @modify:
	 */
	@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT }, value = "doSave")
	public ResponseResult<Object> doSave(@RequestBody(required = false) Map<String, Object> map) {
		try {
			Map<String, Object> resultMap = this.service.doSave(map);
			return ResponseResult.ok(resultMap);
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	/***
	 * @description: 获取合同产品信息
	 * @param paraMap
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/11/25 9:35
	 * @modify:
	 */
	@PostMapping(value = "/copyProductInfo")
	public ResponseResult<Object> copyProductInfo(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			Map<String,Object> result = new HashMap<>();
			List<Map<String, Object>> entities = this.service.copyProductInfo(paraMap);
			String origincontractid = ConvertUtil.convertToString(paraMap.get("origincontractid"));
			LtcContractApplyEntity contractApplyEntity = contractApplyService.queryById(origincontractid);
			// Map<String,Object> contractInfo = contractApplyService.queryMapById(origincontractid);
			result.put("contractinfo",contractApplyEntity.convertToMap());
			result.put("productinfo",entities);
			return ResponseResult.ok(result);
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	/***
	 * @description: 获取决策组成员
	 * @param paraMap
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/11/29 11:35
	 * @modify:
	 */
	@GetMapping("/queryCeo")
	public ResponseResult<Object> queryCeo(
			@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			StringBufferProxy sql = new StringBufferProxy();
			String managercode = "";
			if (paraMap.containsKey("managercode")) {
				//managercode为项目经理工号
				managercode = ConvertUtil.convertToString(paraMap.get("managercode"));
			} else {
				GpmProjectEntity entity = this.service.queryById(paraMap.get("projectid").toString());
				managercode = entity.getProjectmanagercode();
			}
			sql.appendSingle("  ID =(SELECT DEPTID from CBOUSER WHERE CODE='{0}') AND ENABLED=1 ", managercode);
			String code = cboDeptService.queryObjectByWhere(sql.toString()).getCode();
			// 获取扩展信息表
			MmsDeptExtraInfoEntity mmsDeptExtraInfoEntity = this.service.queryDeptCommonCode(code);
			sql.clear();
			List<CboUserEntity> list = cboUserService.queryByWhere(sql.toString());
			if (mmsDeptExtraInfoEntity != null) {
				for (CboUserEntity userinfo : list) {
					if (userinfo.getCode().equals(mmsDeptExtraInfoEntity.getProvincemanagercode())) {
						userinfo.setDescription("sdprovince");
						break;
					}
				}
			}
			return ResponseResult.ok(list);
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	@PutMapping(value = "/projectApproval")
	public ResponseResult<Object> projectApproval(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			this.service.doProjectApproval(paraMap);
			return ResponseResult.ok("合同谈判与签订申请提交成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	protected String spellApprovalListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled = 1 ");
		String value;
		if (paraMap.containsKey("qry_sourceid")) {
			value = paraMap.get("qry_sourceid").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and sourceid = {0} ", value);
			}
		}
		if (paraMap.containsKey("qry_sourcetype")) {
			value = paraMap.get("qry_sourcetype").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and sourcetype = '{0}' ", value);
			}
		}
		return sql.toString();
	}

	/***
	 * @description: 立项审批历史加载页面
	 * @param paraMap
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/11/30 20:35
	 * @modify:
	 */
	@GetMapping({ "/approvalList" })
	public ResponseResult<Object> approvalList(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String qry_wfsourceid = ConvertUtil.convertToString(paraMap.get("qry_wfsourceid"));
			StringBufferProxy sql = new StringBufferProxy();
			// 首先查询对应得审批实体
			sql.appendSingle(" sourcetype = '{0}' and sourceid = '{1}' and businesstype = '{2}' order by submitdate desc "
					, GpmProjectEntity.tableName, qry_wfsourceid, GpmSystemConst.SdApprovalCategory.SdProjectApproval);
			List<GpmWfFormEntity> wfFormEntities = gpmWfFormService.queryByWhere(sql.toString());
			List<Map<String, Object>> tempList = null;
			int totalCount = 0;
			if (wfFormEntities.size() == 0) {
				Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
				return ResponseResult.ok(page);
			}
			paraMap.put("qry_sourceid", wfFormEntities.get(0).getId());
			String sqlWhere = this.spellApprovalListSql(paraMap);
			totalCount = cboApprovalNodeInsService.getCount(sqlWhere);
			if (query.getPageSize() > 0) {
				tempList = cboApprovalNodeInsService.queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord());
			} else {
				tempList = cboApprovalNodeInsService.queryMapByWhere(sqlWhere);
			}
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception var7) {
			return this.handleControllerException(var7);
		}
	}


	@Override
	@GetMapping(value = "/dataCodeList")
	public ResponseResult<Object> dataCodeList(@RequestParam(required = false) Map<String, Object> paraMap) {
		ResponseResult<Object> result = super.dataCodeList(paraMap);
		Map<String, Object> codeMap = (HashMap<String, Object>) result.getResult();
		List<Map<String, Object>> sdApprovalTypeList = datacodeCache.getCodeListMap("GpmApprovalType", "", "sortcode");
		codeMap.put("sdApprovalTypeList", sdApprovalTypeList);
		List<Map<String, Object>> projectstateList = datacodeCache.getCodeListMap("GpmProjectState", "", "sortcode");
		codeMap.put("projectstateList", projectstateList);
		List<Map<String, Object>> supervisestateList = datacodeCache.getCodeListMap("GpmSuperviseState", "", "sortcode");
		codeMap.put("superviseStateList", supervisestateList);
		List<Map<String, Object>> projectlargestateList = datacodeCache.getCodeListMap("GpmProjectLargeState", "", "sortcode");
		codeMap.put("projectlargestateList", projectlargestateList);
		return ResponseResult.ok(codeMap);
	}

	/***
	 * @description: 更新立项部分字段
	 * @param map
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/12/4 10:50
	 * @modify:
	 */
	@PutMapping(value = "/updateProjectPartFields")
	public ResponseResult<Object> updateProjectPartFields(@RequestBody(required = false) Map<String, Object> map) {
		try {
			Map<String, Object> resultMap = new HashMap<String, Object>();
			List<String> queryFields = new ArrayList<String>();
			if(map.containsKey("ismobile")) {
				//获取wfform表数据
				GpmWfFormEntity gpmWfFormEntity = gpmWfFormService.queryById(ConvertUtil.convertToString(map.get("id")));
				map.put("id", ConvertUtil.convertToString(gpmWfFormEntity.getSourceid()));
				if(map.containsKey("invitedecisionusername") && !StringUtil.isEmpty(ConvertUtil.convertToString(map.get("invitedecisionusername")))) {
					List<String> invitedUsers =  Arrays.asList(ConvertUtil.convertToString(map.get("invitedecisionusername")).split(","));
					List<String> invitedCodes = Arrays.asList(ConvertUtil.convertToString(map.get("invitedecisionusercode")).split(","));

					// 获取原始单据
					Map<String,Object> originalMap = this.service.queryMapById(ConvertUtil.convertToString(gpmWfFormEntity.getSourceid()));
					List<String> orginalUsers = Arrays.asList(ConvertUtil.convertToString(originalMap.get("decisionusername")).split(","));
					List<String> orginalCodes = Arrays.asList(ConvertUtil.convertToString(originalMap.get("decisionusercode")).split(","));
					// 遍历姓名去重
					List<String> useUserName = new ArrayList<>();
					for (int i=0; i<invitedUsers.size(); i++) {
						if(!orginalUsers.contains(invitedUsers.get(i))) {
							useUserName.add(invitedUsers.get(i));
						}
					}
					// 工号去重
					List<String> useUserCode = new ArrayList<>();
					for (int i=0; i<invitedCodes.size(); i++) {
						if (!orginalCodes.contains(invitedCodes.get(i))) {
							useUserCode.add(invitedCodes.get(i));
						} else {
							throw new ServiceException("邀请人已包含在决策组成员中，请重新选择");
						}
					}
					// 邀请人员
					String users = useUserName.stream().collect(Collectors.joining(","));
					String decisionusername = useUserName.size() > 0 ?
							ConvertUtil.convertToString(originalMap.get("decisionusername")) + "," + users :
							ConvertUtil.convertToString(originalMap.get("decisionusername"));
					// 邀请人员工号
					String codes = useUserCode.size() > 0 ?
							"," + useUserCode.stream().collect(Collectors.joining(",")) + "," : "";
					String decisionusercode = useUserCode.size() > 0 ?
							ConvertUtil.convertToString(originalMap.get("decisionusercode")) + codes.substring(1) :
							ConvertUtil.convertToString(originalMap.get("decisionusercode"));
					map.put("decisionusercode", decisionusercode);
					map.put("decisionusername", decisionusername);
					map.put("invitedecisionusername", users);
					map.put("invitedecisionusercode", codes);
				}
			}
			for (Map.Entry<String, Object> temp : map.entrySet()) {
				if (!GpmProjectEntity.FieldId.equals(temp.getKey()) && (!"ismobile".equals(temp.getKey()))) {
					queryFields.add(temp.getKey());
				}
			}
			this.service.updateFields(map, queryFields);
			return ResponseResult.ok("修改成功");
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	/***
	 * @description: 加载审批来源id
	 * @param paraMap
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/12/7 20:01
	 * @modify:
	 */
	@Override protected void afterLoad(Map<String, Object> paraMap) {
		super.afterLoad(paraMap);
		String id = ConvertUtil.convertToString(paraMap.get("id"));
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" sourcetype = '{0}' and businesstype = '{1}' and sourceid = '{2}' order by id desc"
				, GpmProjectEntity.tableName, GpmSystemConst.SdApprovalCategory.SdProjectApproval, id);
		List<GpmWfFormEntity> wfFormEntities = gpmWfFormService.queryByWhere(sql.toString());
		if (wfFormEntities.size() > 0) {
			paraMap.put("approvalhistoryid", wfFormEntities.get(0).getId());
		}
		//变更审批sourceid
		StringBufferProxy sqlChange = new StringBufferProxy();
		sqlChange.appendSingle(" finalsourcetype = '{0}' and businesstype = '{1}' and finalsourceid = '{2}' and sourcetype='{3}' order by id desc"
				, GpmProjectEntity.tableName, GpmSystemConst.SdApprovalCategory.SdProjectChange, id, GpmProjectHistoryEntity.tableName);
		List<GpmWfFormEntity> wfFormChangeEntities = gpmWfFormService.queryByWhere(sqlChange.toString());
		if (wfFormChangeEntities.size() > 0) {
			paraMap.put("approvalchangeid", wfFormChangeEntities.get(0).getId());
		}
		// 获取决策人员的二级部门
		if (paraMap.containsKey(GpmProjectEntity.FieldDecisionusercode)) {
			String decisionUserCode = ConvertUtil.convertToString(paraMap.get(GpmProjectEntity.FieldDecisionusercode));
			if (!StringUtil.isEmpty(decisionUserCode)) {
				sql.clear();
				String code = Arrays.stream(decisionUserCode.split(",")).filter(item -> !StringUtil.isEmpty(item)).map(item -> "'" + item + "'").collect(Collectors.joining(","));
				sql.appendSingle(CboUserEntity.FieldCode + " in ({0})", code);
				List<CboUserEntity> userList = cboUserService.queryByWhere(sql.toString());
				Set<Long> deptIdSet = new HashSet<>();
				String deptIdStr = userList.stream().map(CboUserEntity::getDeptid).filter(item -> {
					if (deptIdSet.contains(item)) {
						return false;
					}
					else {
						deptIdSet.add(item);
						return true;
					}
				}).map(item -> "'" + item + "'").collect(Collectors.joining(","));
				List<CboDeptEntity> deptList = cboDeptService.queryByIds(deptIdStr);
				String dispDecisionUserDeptName = deptList.stream().map(CboDeptEntity::getFullname).map(item -> {
					String[] split = item.split("\\\\");
					return split.length > 1 ? split[1] : (split.length > 0 ? split[0] : "");
				}).collect(Collectors.joining("、"));
				paraMap.put("dispdecisionuserdeptname", dispDecisionUserDeptName);
			}
		}
	}

	/**
	 * @return
	 * @throws Exception
	 * @throws
	 * @Title: myOffApprovalList
	 * @return: String
	 * @Description: 手机端返回用户未审批以及审批历史列表以及待审批单据数目
	 */
	@GetMapping(value = "/myApprovalList")
	public ResponseResult<Object> myApprovalList(@RequestParam(required = false) Map<String, Object> paraMap) throws Exception {
		Map result = new HashMap<>();
		List<Map<String, Object>> listDataMap = new ArrayList<Map<String, Object>>();
		String doctType = ConvertUtil.convertToString(paraMap.get("doctype"));
		List<Map<String, Object>> listOffDocTypes = datacodeCache.getCodeListMap(doctType, "", "sortcode");
		StringBufferProxy docType = new StringBufferProxy();
		for (int num = 0; num < listOffDocTypes.size(); num++) {
			if (num != listOffDocTypes.size() - 1) {
				docType.appendSingle("'{0}',", ConvertUtil.convertToString(listOffDocTypes.get(num).get("code")));
			} else {
				docType.appendSingle("'{0}'", ConvertUtil.convertToString(listOffDocTypes.get(num).get("code")));
			}
		}
		Map dataMap = new HashMap<>();
		int page = ConvertUtil.convertToInt(paraMap.get("currentPage"));
		int rows = ConvertUtil.convertToInt(paraMap.get("pageSize"));
		String sidx = ConvertUtil.convertToString(paraMap.get("sidx"));
		String sord = ConvertUtil.convertToString(paraMap.get("sord"));
		String state = ConvertUtil.convertToString(paraMap.get("state"));
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("select tmpTable.*,'ehr' as system from ( ");
		sql.appendSingle(" select  CboApprovalFlowIns.extendfield2 as deptcode,CboApprovalFlowIns.extendfield3 as usercode,CboApprovalFlowIns.submitdate as docdate,CboApprovalFlowIns.extendfield1 as docno,CboApprovalFlowIns.sourcetype as doctype, ");
		sql.appendSingle(
				" CboApprovalNode.name nodename,CboApprovalNode.approvalaction,approvalparam,CboApprovalNode.mobiledataaction,CboApprovalNode.mobileform,CboApprovalNode.extendfield9,CboApprovalNode.extendfield10,CboApprovalNode.ismobilapproval,  ");
		sql.appendSingle(" CboApprovalNodeIns.approvalopinion,");
		sql.appendSingle(
				" CboApprovalNodeIns.id,CboApprovalNodeIns.extendfield2,CboApprovalNodeIns.flowinsid,CboApprovalNodeIns.sourceid,CboApprovalNodeIns.sourcetype,");
		sql.appendSingle(" CboApprovalNodeIns.state,CboApprovalNodeIns.approvaldate ");
		sql.appendSingle(" from CboApprovalNodeIns  ");
		sql.appendSingle(" inner join CboApprovalFlowIns on CboApprovalNodeIns.flowinsid = CboApprovalFlowIns.id ");
		sql.appendSingle(" inner join CboApprovalFlow on CboApprovalFlowIns.flowid = CboApprovalFlow.id ");
		sql.appendSingle(" inner join CboApprovalNode on CboApprovalNodeIns.nodeid = CboApprovalNode.id ");
		sql.appendSingle(" left join CboDept on CboApprovalFlowIns.extendfield2 = CboDept.code ");
		sql.appendSingle(" left join CboUser on CboApprovalFlowIns.extendfield3 = CboUser.code ");
		if (paraMap.containsKey("qry_doctype")) {
			String value = paraMap.get("qry_doctype").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" where CboApprovalNodeIns.sourcetype = '{0}' ", value);
			} else {
				sql.appendSingle(" where CboApprovalNodeIns.sourcetype in ({0}) ", docType);
			}
		} else {
			sql.appendSingle(" where CboApprovalNodeIns.sourcetype in ({0}) ", docType);
		}
		if (this.getUserBean() != null) {
			if (paraMap.containsKey("indexApp")) {
				if (paraMap.get("indexApp").toString().equals("1")) {

				} else {
					sql.appendSingle(" and CboApprovalNodeIns.approvaluserid ='{0}'",
							this.getUserBean().getUser().getId());
				}
			} else {
				sql.appendSingle(" and CboApprovalNodeIns.approvaluserid ='{0}'",
						this.getUserBean().getUser().getId());
			}
		} else {
			return ResponseResult.ok("登录超时");
		}
		sql.appendSingle(" and CboApprovalNodeIns.state in ({0}) ", state);
		if (paraMap.containsKey("qry_dispdeptcode")) {
			String value = paraMap.get("qry_dispdeptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and CboDept.name like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_dispusercode")) {
			String value = paraMap.get("qry_dispusercode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and CboUser.name like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_usercode")) {
			String value = paraMap.get("qry_usercode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and CboUser.code = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_startdocdate")) {
			String value = paraMap.get("qry_startdocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and CboApprovalFlowIns.submitdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and CboApprovalFlowIns.submitdate <= {0} ", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		sql.appendSingle(" ) tmpTable where ismobilapproval=1");
		int records = cboApprovalNodeInsService.selectCountExecute(sql.toString());
		dataMap = new HashMap();
		dataMap.put("records", records);
		dataMap.put("docTypes", listOffDocTypes);
		if (!paraMap.containsKey("count")) {
			listDataMap = cboApprovalNodeInsService.selectExecuteForPage(sql.toString(), page, rows, sidx, sord);
			for (Map mapRow : listDataMap) {
				setDispFields(mapRow, listOffDocTypes, doctType);
			}
		}
		result.put("dataMap", dataMap);
		result.put("dataList", listDataMap);
		return ResponseResult.ok(result);
	}
	private void setDispFields(Map mapRow, List<Map<String, Object>> listOffDocTypes, String doctype) {
		DatacodeCache datacodeCache = (DatacodeCache) SpringUtil.getBean("datacodeCache");
		String temp = "";
		if (mapRow.get("state") != null) {
			temp = mapRow.get("state").toString();
			mapRow.put("dispstate", datacodeCache.getValueDynamic("TapApprovalNodeState", temp, "code", "name"));
		}
		if (mapRow.get("usercode") != null) {
			temp = mapRow.get("usercode").toString();
			mapRow.put("username", datacodeCache.getValueDynamic("CboUser", temp, "code", "name"));
		}
		if (mapRow.get("orgcode") != null) {
			temp = mapRow.get("orgcode").toString();
			mapRow.put("disporgcode", datacodeCache.getValueDynamic("CboOrg", temp, "code", "name"));
		}
		if (mapRow.get("deptcode") != null) {
			// 研发本部展示具体部门，其他的展示一级部门
			temp = mapRow.get("deptcode").toString();
			if (temp.startsWith("2201") || temp.startsWith("2212") || temp.startsWith("D1F01_0101") || temp.startsWith("2404") || temp.startsWith("D101")) {
				mapRow.put("dispdeptcode", datacodeCache.getValueDynamic("CboDept", temp, "code", "name"));
			} else {
				// 获取一级部门
				String fullname = datacodeCache.getValueDynamic("CboDeptFull", temp, "code", "name");
				mapRow.put("dispdeptcode", fullname.split("\\\\")[1]);
			}
		}
		if (mapRow.get("nodetype") != null) {
			temp = mapRow.get("nodetype").toString();
			mapRow.put("dispnodetype", datacodeCache.getValueDynamic("TapApprovalNodeType", temp, "code", "name"));
		}
		if (mapRow.get("extendfield2") == null || mapRow.get("extendfield2").toString().equals("")) {
			if (listOffDocTypes != null) {
				temp = mapRow.get("nodename").toString();
				mapRow.put("extendfield2", temp);
			} else {
				temp = mapRow.get("dispnodeid").toString();
				mapRow.put("extendfield2", temp);
			}

		}
		if (mapRow.get("doctype") != null && listOffDocTypes != null) {
			temp = mapRow.get("doctype").toString();
			for (Map listOffDocType : listOffDocTypes) {

				if (temp.equals(listOffDocType.get("code"))) {
					mapRow.put("dispdoctype", datacodeCache.getValueDynamic(doctype, temp, "code", "name"));
					if (StringUtil.isEmpty(ConvertUtil.convertToString(listOffDocType.get("extendfield1")))) {
						if ("1".equals(ConvertUtil.convertToString(listOffDocType.get("extendfield1")))) {
							mapRow.put("webDesign", "1");//电脑端配置详情页
						}
					} else {
						mapRow.put("webDesign", "0");//老的详情页
					}

					break;
				}
			}
		}
	}

	/**
	 * 2021-12-27 zhangjunyao
	 * @return
	 * @throws Exception
	 * @throws
	 * @Title:
	 * @return: ResponseResult
	 * @Description: 重写list方法联表查询督办情况(项目监管用）
	 */
	@GetMapping({"/listForQuery"})
	public ResponseResult<Object> listForQuery(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = this.spellListSql(paraMap);
			Map<String, Object> sqlMap = new HashMap<>();
			sqlMap.put("whereSql", sqlWhere);
			int totalCount = this.service.getCount1(sqlMap,"querySdProjectByWhere");
			List<Map<String, Object>> tempList = null;
			if (query.getPageSize() > 0) {
				tempList = this.service.queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord(), "querySdProjectForPage");
			} else {
				tempList = this.service.queryMap(sqlMap,"querySdProjectByWhere");
			}
			this.service.setDispFields(tempList);
			// 拼接督办字段
			gpmProjectSuperviseService.getSuperviseList(tempList);
			// 拼接立项、任命、策划、复盘开始结束时间字段
			this.getVariousDateForSuperVise(tempList);
			// 拼接执行情况
			Map<String,String> tempMap = this.service.getProjectState(tempList);
			if(tempMap!=null) {
				for(Map<String,Object> temp:tempList) {
					if("7".equals(ConvertUtil.convertToString(temp.get("projectstate")))) {
						String projectcode = ConvertUtil.convertToString(temp.get("projectcode"));
						if(tempMap.containsKey(projectcode)) {
							temp.put("dispprojectstate",tempMap.get(projectcode));
						}
					}
				}
			}
			this.service.dealWithChangeOwnerPermission(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}
	/**
	 * @author: houyuhang
	 * @date: 2022-01-07
	 * @description: 根据机会点编号获取销售项目编号
	 * @modify:
	 */
	@GetMapping(value = "/mpmProjectCode")
	public ResponseResult<Object> mpmProjectCode(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			Map<String,Object> res = this.service.mpmProjectCode(paraMap);
			return ResponseResult.ok(res);
		} catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}

	/**
	 * @author: zhangjunyao
	 * @date: 2022-01-18
	 * @description: 判断决策组会签节点是否有人退回
	 * @modify:
	 */
	@GetMapping(value = "/ifApprovalBack")
	public ResponseResult<Object> ifApprovalBack(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			boolean ifApprovalBack = false;
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String projectId = "";
			if (paraMap.containsKey("projectid")) {
				projectId = ConvertUtil.convertToString(paraMap.get("projectid"));
				ifApprovalBack = this.service.ifApprovalBack(projectId);
			}
			return ResponseResult.ok(ifApprovalBack);
		} catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}

	/**
	 * @author: zhangjunyao
	 * @date: 2022-01-18
	 * @description: 重写取消审批方法，去除权限判断
	 * @modify:
	 */
	@DeleteMapping({"/delApproval"})
	@Override
	public ResponseResult<Object> delApproval(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			String id = ConvertUtil.convertToString(paraMap.get("id"));
			this.service.executeDelApprove(id);
			return ResponseResult.ok("取消审批成功");
		} catch (Exception ex) {
			return this.handleControllerException(ex);
		}
	}

	@GetMapping({"/list"})
	public ResponseResult<Object> list(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = this.spellListSql(paraMap);
			int totalCount = this.service.getCount(sqlWhere);
			List<Map<String, Object>> tempList = null;
			if (query.getPageSize() > 0) {
				tempList = ((ITapService)this.service).queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord());
			} else {
				tempList = ((ITapService)this.service).queryMapByWhere(sqlWhere);
			}
			if (!paraMap.containsKey("qry_open")&&paraMap.containsKey("qry_projectmanagermenu")) {
				// 拼接执行情况
				Map<String,String> tempMap = this.service.getProjectState(tempList);
				if(tempMap!=null) {
					for(Map<String,Object> temp:tempList) {
						if("7".equals(ConvertUtil.convertToString(temp.get("projectstate")))) {
							String projectcode = ConvertUtil.convertToString(temp.get("projectcode"));
							if(tempMap.containsKey(projectcode)) {
								temp.put("dispprojectstate",tempMap.get(projectcode));
							}
						}
					}
				}
			}
			if(paraMap.containsKey("qry_projectmanagermenu")){
				String qry_projectmanagermenu = ConvertUtil.convertToString(paraMap.get("qry_projectmanagermenu"));
				if("1".equals(qry_projectmanagermenu)) {
					this.service.dealWithChangeOwnerPermission(tempList);
				}
			}
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception var7) {
			return this.handleControllerException(var7);
		}
	}

	/**
	 * @Title: 获取立项、任命、策划、复盘的审批开始、结束时间
	 * @description: 具体逻辑：1、主表的projectcode关联任命、策划、复盘表的projectcode，取第一次任命、策划，主表id关联wfform表sourceID 对应集合为resultMap
	 * 2、wfform表、任命、策划、复盘表id关联cboAppNodeIns表sourceid字段，对应集合为nodeInsEntities 3、setVariousDate方法中取到对应开始结束时间
	 * @param
	 * @return
	 * @author: houyuhang
	 * @date: 2022年03月09日
	 * @modify:
	 */
	private void getVariousDateForSuperVise(List<Map<String, Object>> tempList) {
		StringBufferProxy sql = new StringBufferProxy();
		String ids = tempList.stream().map(map -> ConvertUtil.convertToString(map.get("id")))
				.collect(Collectors.joining("','", "'", "'"));
		String projectCodes = tempList.stream().map(map -> ConvertUtil.convertToString(map.get("projectcode")))
				.collect(Collectors.joining("','", "'", "'"));
		Map<String, List<Map<String, Object>>> resultMap;
		// 查询立项开始时间
		sql.clear();
		sql.appendSingle(" {0} in ({1}) and {2} = '{3}' ", GpmWfFormEntity.FieldSourceid, ids, GpmWfFormEntity.FieldSourcetype, "GpmProject");
		List<Map<String, Object>> wfFormList = gpmWfFormService.queryMapByWhere(sql.toString());
		String sourceIds = wfFormList.stream().map(map -> ConvertUtil.convertToString(map.get("id")))
				.collect(Collectors.joining("','", "'", "'"));
		resultMap = wfFormList.stream().collect(Collectors.groupingBy(map -> ConvertUtil.convertToString(map.get("sourceid"))));
		List<CboApprovalNodeInsEntity> nodeInsEntities = queryApprovalTime(sourceIds, GpmWfFormEntity.tableName, GpmSystemConst.ApprovalState.Begin);
		setVariousDate(tempList, nodeInsEntities, GpmProjectEntity.tableName, resultMap, "submitbegindate");
		// 查询立项结束时间
		nodeInsEntities = queryApprovalTime(sourceIds, GpmWfFormEntity.tableName, GpmSystemConst.ApprovalState.End);
		setVariousDate(tempList, nodeInsEntities, GpmProjectEntity.tableName, resultMap, "submitfinishdate");
		// 查询任命开始时间
		sql.clear();
		sql.appendSingle(" {0} in ({1}) and {2} = {3} ", GpmProjectAppointmentEntity.FieldProjectcode, projectCodes, GpmProjectAppointmentEntity.FieldVersion, GpmSystemConst.FirstVersion);
		List<Map<String, Object>> appointmentList = gpmProjectAppointmentService.queryMapByWhere(sql.toString());
		sourceIds = appointmentList.stream().map(map -> ConvertUtil.convertToString(map.get("id")))
				.collect(Collectors.joining("','", "'", "'"));
		resultMap = appointmentList.stream().collect(Collectors.groupingBy(map -> ConvertUtil.convertToString(map.get("projectcode"))));
		nodeInsEntities = queryApprovalTime(sourceIds, GpmProjectAppointmentEntity.tableName, GpmSystemConst.ApprovalState.Begin);
		setVariousDate(tempList, nodeInsEntities, GpmProjectAppointmentEntity.tableName, resultMap, "appointbegindate");
		// 查询任命结束时间
		nodeInsEntities = queryApprovalTime(sourceIds, GpmProjectAppointmentEntity.tableName, GpmSystemConst.ApprovalState.End);
		setVariousDate(tempList, nodeInsEntities, GpmProjectAppointmentEntity.tableName,resultMap, "appointfinishdate");
		// 查询策划开始时间
		sql.clear();
		sql.appendSingle(" {0} in ({1}) and {2} = {3} ", GpmProjectPlanEntity.FieldProjectcode, projectCodes, GpmProjectPlanEntity.FieldVersion, GpmSystemConst.FirstVersion);
		List<Map<String, Object>> planList = gpmProjectPlanService.queryMapByWhere(sql.toString());
		sourceIds = planList.stream().map(map -> ConvertUtil.convertToString(map.get("id")))
				.collect(Collectors.joining("','", "'", "'"));
		resultMap = planList.stream().collect(Collectors.groupingBy(map -> ConvertUtil.convertToString(map.get("projectcode"))));
		nodeInsEntities = queryApprovalTime(sourceIds, GpmProjectPlanEntity.tableName, GpmSystemConst.ApprovalState.Begin);
		setVariousDate(tempList, nodeInsEntities, GpmProjectPlanEntity.tableName, resultMap, "planbegindate");
		// 查询策划结束时间
		nodeInsEntities = queryApprovalTime(sourceIds, GpmProjectPlanEntity.tableName, GpmSystemConst.ApprovalState.End);
		setVariousDate(tempList, nodeInsEntities, GpmProjectPlanEntity.tableName, resultMap, "planfinishdate");
		// 查询复盘开始时间
		sql.clear();
		sql.appendSingle(" {0} in ({1}) ", GpmProjectReviewEntity.FieldProjectcode, projectCodes);
		List<Map<String, Object>> reviewList = gpmProjectAppointmentService.queryMapByWhere(sql.toString());
		sourceIds = reviewList.stream().map(map -> ConvertUtil.convertToString(map.get("id")))
				.collect(Collectors.joining("','", "'", "'"));
		resultMap = reviewList.stream().collect(Collectors.groupingBy(map -> ConvertUtil.convertToString(map.get("projectcode"))));
		nodeInsEntities = queryApprovalTime(sourceIds, GpmProjectReviewEntity.tableName, GpmSystemConst.ApprovalState.Begin);
		setVariousDate(tempList, nodeInsEntities, GpmProjectReviewEntity.tableName, resultMap, "reviewbegindate");
		// 查询复盘结束时间
		nodeInsEntities = queryApprovalTime(sourceIds, GpmProjectReviewEntity.tableName, GpmSystemConst.ApprovalState.End);
		setVariousDate(tempList, nodeInsEntities, GpmProjectReviewEntity.tableName,resultMap, "reviewbegindate");
	}
	/**
	 * @Title: 封装立项、任命、策划、复盘的审批开始、结束时间
	 * @description:
	 * @param
	 * @return
	 * @author: houyuhang
	 * @date: 2022年03月09日
	 * @modify:
	 */
	private void setVariousDate(List<Map<String, Object>> tempList, List<CboApprovalNodeInsEntity> nodeInsEntities,
								String tableName, Map<String, List<Map<String, Object>>> resultMap, String dateName) {
		if (nodeInsEntities.isEmpty()) {
			return;
		}
		// 转化为以sourceid区分的时间map
		Map<String, List<CboApprovalNodeInsEntity>> nodeInsMap = nodeInsEntities.stream().collect(Collectors
				.groupingBy(map -> ConvertUtil.convertToString(map.getSourceid())));
		for (Map<String, Object> mapRow : tempList) {
			// 若是立项则id从templist中获取，否则从resultmap中获取
			String projectCode = ConvertUtil.convertToString(mapRow.get("projectcode")), id = "";
			String sourceid = ConvertUtil.convertToString(mapRow.get("id"));
			if (tableName.equals(GpmProjectEntity.tableName)) {
				if (resultMap.containsKey(sourceid)) {
					id = ConvertUtil.convertToString(resultMap.get(sourceid).get(0).get("id"));
				}
			} else {
				if (resultMap.containsKey(projectCode)) {
					id = ConvertUtil.convertToString(resultMap.get(projectCode).get(0).get("id"));
				}
			}
			if (nodeInsMap.containsKey(id)) {
				// 因为只显示第一次任命/策划的时间，所以直接选择第一个
				CboApprovalNodeInsEntity nodeInsEntity = nodeInsMap.get(id).get(0);
				mapRow.put(dateName, nodeInsEntity.getApprovaldate());
			}
		}
	}
	/**
	 * @Title: 查询任命、策划、复盘的审批开始、结束时间
	 * @description:
	 * @param
	 * @return
	 * @author: houyuhang
	 * @date: 2022年03月09日
	 * @modify:
	 */
	private List<CboApprovalNodeInsEntity> queryApprovalTime(String sourceIds,String tableName,String approvalState) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" {0} in ({1}) and {2} = '{3}' and {4} = '{5}' order by {6} ", CboApprovalNodeInsEntity.FieldSourceid, sourceIds,
				CboApprovalNodeInsEntity.FieldSourcetype, tableName, CboApprovalNodeInsEntity.FieldExtendfield2,
				approvalState, CboApprovalNodeInsEntity.FieldApprovaldate);
		List<CboApprovalNodeInsEntity> nodeInsEntities = cboApprovalNodeInsService.queryByWhere(sql.toString());
		return nodeInsEntities;
	}
	/**
	 * @Title: 获取deptcode对应的deptcommoncode
	 * @description:
	 * @param
	 * @return
	 * @author: houyuhang
	 * @date: 2022年03月17日
	 * @modify:
	 */
	@GetMapping(value = "/queryDeptCommonCode")
	public ResponseResult<Object> queryDeptCommonCode(@RequestParam(required = false) Map<String,Object> paraMap) {
		String deptcode = ConvertUtil.convertToString(paraMap.get("deptcode"));
		String deptCommonCode1 = mmsDeptExtraInfoService.getDeptCommonCode(deptcode);
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("deptcommoncode1", deptCommonCode1);
		return ResponseResult.ok(resultMap);
	}
	/**
	 * @description:判断切换后的人员是否在当前等级下可以被选中
	 * @param
	 * @return
	 * @author: houyuhang
	 * @date: 2022年05月19日
	 * @modify:
	 */
	@GetMapping(value = "/judgeDecisionUser")
	public ResponseResult<Object> judgeDecisionUser(@RequestParam(required = false) Map<String,Object> paraMap) {
		try {
			String decisionusercode = ConvertUtil.convertToString(paraMap.get("decisionusercode"));
			String decisionusername = ConvertUtil.convertToString(paraMap.get("decisionusername"));
			Map<String, Object> resultMap = new HashMap<>();
			StringBufferProxy sql = new StringBufferProxy();
			// 判断切换后的人员是否在当前等级下可以被选中
			sql.appendSingle(" instr('{0}', {1}) > 0 and projectlevel not like '%{2}%' ", decisionusercode,
					SQLAdapter.concat(new String[]{"','", GpmProjectResourcePoolEntity.FieldUsercode , "','"}), ConvertUtil.convertToString(paraMap.get("newlevel")));
			List<GpmProjectResourcePoolEntity> sdProjectResourcePoolEntities = gpmProjectResourcePoolService.queryByWhere(sql.toString());
			if (CollectionUtil.isEmpty(sdProjectResourcePoolEntities)) {
				resultMap.put("newdecisionusercode", decisionusercode);
				resultMap.put("newdecisionusername", decisionusername);
			}
			List<String> decisionusercodeList = Arrays.stream(decisionusercode.split(",")).filter(item -> !StringUtil.isEmpty(item)).collect(Collectors.toList());
			List<String> decisionusernameList = Arrays.stream(decisionusername.split(",")).filter(item -> !StringUtil.isEmpty(item)).collect(Collectors.toList());
			for(GpmProjectResourcePoolEntity gpmProjectResourcePoolEntity : sdProjectResourcePoolEntities) {
				decisionusercodeList.remove(gpmProjectResourcePoolEntity.getUsercode());
				decisionusernameList.remove(gpmProjectResourcePoolEntity.getUsername());
			}
			resultMap.put("newdecisionusercode", CollectionUtil.isEmpty(decisionusercodeList) ? "" : "," + decisionusercodeList.stream().collect(Collectors.joining(",")) + ",");
			resultMap.put("newdecisionusername", CollectionUtil.isEmpty(decisionusernameList) ? "" : decisionusernameList.stream().collect(Collectors.joining(",")));
			return ResponseResult.ok(resultMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}


	public void setContractDispFields(List<Map<String, Object>> mapRowList) {
		DatacodeCache datacodeCache = (DatacodeCache) SpringUtil.getBean("datacodeCache");
		for (Map<String, Object> mapRow : mapRowList) {
			setContractDispFields1(mapRow, datacodeCache);
		}
	}

	public void setContractDispFields1(Map<String, Object> mapRow, DatacodeCache datacodeCache) {
		String temp;
		if (mapRow.get("predeptcode") != null) {
			temp = mapRow.get("predeptcode").toString();
			mapRow.put("disppredeptcode", datacodeCache.getValueDynamic("CboDeptFull", temp, "code", "name"));
		}
		if (mapRow.get("deptcode") != null) {
			temp = mapRow.get("deptcode").toString();
			mapRow.put("dispdeptcode", datacodeCache.getValueDynamic("CboDeptFull", temp, "code", "name"));
		}
		if (mapRow.get("deptcommoncode1") != null) {
			temp = mapRow.get("deptcommoncode1").toString();
			mapRow.put("dispdeptcommoncode1", datacodeCache.getValueDynamic("DeptCommonCode", temp, "code", "name"));
		}
		if (mapRow.get("negotiationsource") != null) {
			temp = mapRow.get("negotiationsource").toString();
			mapRow.put("dispnegotiationsource", datacodeCache.getValueDynamic("ContractNegotiationSource", temp, "code", "name"));
		}
		if (mapRow.get("customercategory") != null) {
			temp = mapRow.get("customercategory").toString();
			mapRow.put("dispcustomercategory", datacodeCache.getValueDynamic("CpCustomerClass", temp, "code", "name"));
		}
		if (mapRow.get("contractorgcode") != null) {
			temp = mapRow.get("contractorgcode").toString();
			mapRow.put("dispcontractorgcode", datacodeCache.getValueDynamic("ContractOrgcode", temp, "code", "name"));
		}
		if (mapRow.get("contractnsource") != null) {
			temp = mapRow.get("contractnsource").toString();
			mapRow.put("dispcontractnsource", datacodeCache.getValueDynamic("ContractNegotiationSource", temp, "code", "name"));
		}
		if (mapRow.get("billtypeismatched") != null) {
			temp = mapRow.get("billtypeismatched").toString();
			mapRow.put("dispbilltypeismatched", datacodeCache.getValueDynamic("ContractBillType", temp, "code", "name"));
		}
		if (mapRow.get("approvalstate") != null) {
			temp = mapRow.get("approvalstate").toString();
			mapRow.put("dispapprovalstate", datacodeCache.getValueDynamic("ContractApprovalState", temp, "code", "name"));
		}
		if (mapRow.get("contractexecutestate") != null) {
			temp = mapRow.get("contractexecutestate").toString();
			mapRow.put("dispcontractexecutestate", datacodeCache.getValueDynamic("ContractExecuteState", temp, "code", "name"));
		}
		if (mapRow.get("category") != null) {
			temp = mapRow.get("category").toString();
			mapRow.put("dispcategory", datacodeCache.getValueDynamic("ContractCategory", temp, "code", "name"));
		}
		if (mapRow.get("whetherframeworkaggrement") != null) {
			temp = mapRow.get("whetherframeworkaggrement").toString();
			mapRow.put("dispwhetherframeworkaggrement", datacodeCache.getValueDynamic("CboYesNo", temp, "code", "name"));
		}
		if (mapRow.get("whetherneedcontract") != null) {
			temp = mapRow.get("whetherneedcontract").toString();
			mapRow.put("dispwhetherneedcontract", datacodeCache.getValueDynamic("CboYesNo", temp, "code", "name"));
		}
		if (mapRow.get("contractstate") != null) {
			temp = mapRow.get("contractstate").toString();
			mapRow.put("dispcontractstate", datacodeCache.getValueDynamic("ContractState", temp, "code", "name"));
		}
		if (mapRow.get("accountperiod") != null) {
			temp = mapRow.get("accountperiod").toString();
			mapRow.put("dispaccountperiod", datacodeCache.getValueDynamic("ContractAccountPeriod", temp, "code", "name"));
		}
		if (mapRow.get("whethertemplate") != null) {
			temp = mapRow.get("whethertemplate").toString();
			mapRow.put("dispwhethertemplate", datacodeCache.getValueDynamic("CboYesNo", temp, "code", "name"));
		}
		if (mapRow.get("usernature") != null) {
			temp = mapRow.get("usernature").toString();
			mapRow.put("dispusernature", datacodeCache.getValueDynamic("ContractUserNature", temp, "code", "name"));
		}
		if (mapRow.get("acceptancenature") != null) {
			temp = mapRow.get("acceptancenature").toString();
			mapRow.put("dispacceptancenature", datacodeCache.getValueDynamic("ContractAcceptanceNature", temp, "code", "name"));
		}
		if (mapRow.get("currentphase") != null) {
			temp = mapRow.get("currentphase").toString();
			mapRow.put("dispcurrentphase", datacodeCache.getValueDynamic("ContractPhase", temp, "code", "name"));
		}
		if (mapRow.get("processmethod") != null) {
			temp = mapRow.get("processmethod").toString();
			mapRow.put("dispprocessmethod", datacodeCache.getValueDynamic("ContractProcessMethod", temp, "code", "name"));
		}
		if (mapRow.get("productline") != null) {
			temp = mapRow.get("productline").toString();
			mapRow.put("dispproductline", datacodeCache.getValueDynamic("ProductLine", temp, "code", "name"));
		}
		if (mapRow.get("enabled") != null) {
			temp = mapRow.get("enabled").toString();
			mapRow.put("dispenabled", datacodeCache.getValueDynamic("CboYesNo", temp, "code", "name"));
		}
		if (mapRow.get("shareareas") != null) {
			temp = mapRow.get("shareareas").toString();
			mapRow.put("dispshareareas", datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", temp, "code", "name"));
		}
		if (mapRow.get("deptname2") != null) {
			temp = mapRow.get("deptname2").toString();
			mapRow.put("dispdeptname2", datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", temp, "code", "name"));
		}
		if (mapRow.get("approvaldepts") != null) {
			temp = mapRow.get("approvaldepts").toString();
			mapRow.put("dispapprovaldepts", datacodeCache.getValueDynamic("ContractApprovalProductLine", temp, "code", "name"));
		}
		if (mapRow.get("createuser") != null) {
			temp = mapRow.get("createuser").toString();
			mapRow.put("dispcreateuser", datacodeCache.getValueDynamic("CboUser", temp, "id", "name"));
		}
		if (mapRow.get("deptname1") != null) {
			temp = "";
			String temp1 = ConvertUtil.convertToString(mapRow.get("deptname1"));
			String temp2 = ConvertUtil.convertToString(mapRow.get("deptname2"));
			String temp3 = ConvertUtil.convertToString(mapRow.get("deptname3"));
			if(!"".equals(temp3)) {
				temp = datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", temp1, "code", "name")+"/"
						+datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", temp2, "code", "name")+"/"
						+datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", temp3, "code", "name");
			}else if(!"".equals(temp2)){
				temp = datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", temp1, "code", "name")+"/"
						+datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", temp2, "code", "name");
			}else {
				temp =  datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", temp1, "code", "name");
			}
			mapRow.put("dispdeptname",temp);
		} else {
			mapRow.put("dispdeptname","");
		}
		if(mapRow.get("levelcode") != null){
			temp = mapRow.get("levelcode").toString();
			mapRow.put("displevelcode", datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", temp, "code", "name"));
		}
	}
	@PutMapping(value = "/changeOwner")
	public ResponseResult<Object> changeOwner(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			this.service.changeOwner(paraMap);
			return ResponseResult.ok("提交成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	@GetMapping({"/userList"})
	public ResponseResult<Object> userList(@RequestParam(required = false) Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		Query query = new Query(paraMap);
		String sqlWhere = this.spellUserListSql(paraMap);
		int totalCount = cboUserService.getCount(sqlWhere);
		List<Map<String, Object>> tempList = null;
		if (query.getPageSize() > 0) {
			tempList = cboUserService.queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord(), "com.topscomm.gpm.pojo.GpmProjectEntity.queryUserMapForPage");
		} else {
			tempList = cboUserService.queryMapByWhere(sqlWhere, "com.topscomm.gpm.pojo.GpmProjectEntity.queryUserMapForPage");
		}

		cboUserService.setDispFields(tempList);
		Iterator var6 = tempList.iterator();

		while(var6.hasNext()) {
			Map<String, Object> user = (Map)var6.next();
			user.remove("userpassword");
		}

		Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
		return ResponseResult.ok(page);
	}
	/**
	 * @description: 人员参照重写的
	 * @param paraMap
	 * @return java.lang.String
	 * @author: wangxinhua
	 * @date: 2021/8/25 10:48
	 * @modify:
	 */
	protected String spellUserListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		String value;
		if (paraMap.containsKey("qry_name")) {
			value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and name like '%{0}%' ", value);
			}
		}

		if (paraMap.containsKey("qry_code")) {
			value = paraMap.get("qry_code").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and code like '%{0}%' ", value);
			}
		}

		if (paraMap.containsKey("qry_namecode")) {
			value = paraMap.get("qry_namecode").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and (name  like '%{0}%' or code like '%{0}%') ", value);
			}
		}

		if (paraMap.containsKey("qry_nodimission")) {
			value = paraMap.get("qry_nodimission").toString();
			if ("1".equals(value)) {
				sql.appendSingle(" and dimissiondate is null ", value);
			}
		}

		if (paraMap.containsKey("qry_deptid")) {
			value = paraMap.get("qry_deptid").toString();
			if (!StringUtil.isEmpty(value)) {
				if (paraMap.containsKey("qry_includeSub")) {
					String include = paraMap.get("qry_includeSub").toString();
					if (!StringUtil.isEmpty(include) && "true".equals(include)) {
						CboDeptService deptService = (CboDeptService) SpringUtil.getBean("cboDeptService");
						CboDeptEntity deptEntity = deptService.queryById(value);
						if (deptEntity != null) {
							sql.appendSingle(" and deptid in (select id from cbodept where code like '{0}%') ", deptEntity.getCode());
						}
					} else {
						sql.appendSingle(" and deptid = '{0}' ", value);
					}
				} else {
					sql.appendSingle(" and deptid = '{0}' ", value);
				}
			}
		}

		if (paraMap.containsKey("qry_orgid")) {
			value = paraMap.get("qry_orgid").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and orgid = '{0}' ", value);
			}
		}

		if (paraMap.containsKey("qry_roleid")) {
			value = paraMap.get("qry_roleid").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(" and id in (select userid from cbouserrole where roleid = '{0}' )", value);
			}
		}

		if (paraMap.containsKey("qry_groupid")) {
			value = paraMap.get("qry_groupid").toString();
			if (!StringUtil.isEmpty(value)) {
				List<String> filedList = new ArrayList();
				String userKey = ParameterCache.getValue("CboUserKey", "code");
				String usercodes;
				Map groupMap;
				if (userKey.equals(CboSystemConst.CboKeyEnum.Code)) {
					filedList.add(SQLAdapter.toChar("groupusercodes") + " as groupusercodes");
					groupMap = this.cboUserGroupService.queryFieldsById(value, filedList);
					usercodes = ConvertUtil.convertToString(groupMap.get("groupusercodes")).replace(",", "','");
					sql.appendSingle(" and code in ('{0}')", usercodes);
				} else {
					filedList.add(SQLAdapter.toChar("groupuserids") + " as groupuserids");
					groupMap = this.cboUserGroupService.queryFieldsById(value, filedList);
					usercodes = ConvertUtil.convertToString(groupMap.get("groupuserids"));
					sql.appendSingle(" and id in ({0})", usercodes);
				}
			}
		}

		if (paraMap.containsKey("qry_idlist")) {
			value = paraMap.get("qry_idlist").toString();
			if (!StringUtil.isEmpty(value)) {
				if (value.endsWith(",")) {
					value = value.substring(0, value.length() - 1);
				}

				if (value.startsWith(",")) {
					value = value.substring(1);
				}

				sql.appendSingle(" and id in ({0})", value);
			}
		}

		if (paraMap.containsKey("qry_codelist")) {
			value = paraMap.get("qry_codelist").toString();
			if (!StringUtil.isEmpty(value)) {
				if (value.endsWith(",")) {
					value = value.substring(0, value.length() - 1);
				}

				if (value.startsWith(",")) {
					value = value.substring(1);
				}

				sql.appendSingle(" and code in ('{0}')", value.replaceAll(",", "','"));
			}
		}

		if (paraMap.containsKey("qry_whereSql")) {
			value = paraMap.get("qry_whereSql").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendLineSingle(" and {0} ", value);
			}
		}
		if (paraMap.containsKey("qry_firstdeptcode")) {
			value = paraMap.get("qry_firstdeptcode").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendLineSingle(" and deptid in ( select id from CBODEPT where concat(',',code) like '%,{0}%' AND code NOT LIKE '%,{0}%' ) ", value);
			}
		}
		return sql.toString();
	}

	@GetMapping(value = "/queryCanWatch")
	public ResponseResult<Object> queryCanWatch(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			Map<String, Object> resultMap = new HashMap<>();
			String JYGLBRole = GpmSystemConst.sdJYGLBRole;
			boolean canWatch = false;
			boolean whetherpmo = false;
			List<CboRoleEntity> roleList = this.getUserBean().getRoleList();
			for (CboRoleEntity roleEntity : roleList) {
				// 排除角色code为空的情况
				if (StringUtil.isEmpty(roleEntity.getCode())) {
					continue;
				}
				if (JYGLBRole.contains("," + roleEntity.getCode() + ",")) {
					whetherpmo = true;
					break;
				}
			}
			resultMap.put("whetherpmo", whetherpmo);
			return ResponseResult.ok(resultMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
			// 如果当前用户的角色列表中包含任意一个系统参数中配置角色,可以进行关注与留言
	/**
	 * @description:判断用户是否为SD PMO，可以选择公开/取消公开
	 * @author: houyuhang
	 * @date: 2022年09月05日
	 * @modify:
	 */
	@GetMapping(value = "/queryIsPMO")
	public ResponseResult<Object> queryIsPMO(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			Map<String, Object> resultMap = new HashMap<>();
			String JYGLBRole = GpmSystemConst.JYGLBRole;
			boolean whetherpmo = false;
			// 判断角色中是否存在SD PMO
			List<CboRoleEntity> roleList = this.getUserBean().getRoleList();
			for(CboRoleEntity roleEntity:roleList) {
				// 排除角色code为空的情况
				if (StringUtil.isEmpty(roleEntity.getCode())) {
					continue;
				}
				if (JYGLBRole.contains("," + roleEntity.getCode() + ",")) {
					whetherpmo = true;
					break;
				}
			}
			resultMap.put("whetherpmo", whetherpmo);
			return ResponseResult.ok(resultMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	/***
	 * @description: 立项置顶功能
	 * @param paraMap
	 * @return
	 * @author: jiangtao1
	 * @date: 2022/8/9 14:31
	 * @modify:
	 */
	@PutMapping({"/changeTop"})
	public ResponseResult<Object> changeTop(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			return ResponseResult.ok(this.service.changeTop(paraMap));
		} catch (Exception e) {
			return this.handleControllerException(e);
		}
	}
	/**
	 * @description: fds系统获取人员能查看的销售项目数据
	 * @author houyuhang
	 * @date 2022/12/21
	 * @modify
	 */
	@GetMapping("/listForFMS")
	public ResponseResult<Object> listForFMS(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			// 校验FMS系统传递key值
			String fmsToken = ParameterCache.getValue("FmsTokenProject");
			if (!fmsToken.equals(ConvertUtil.convertToString(paraMap.get("appKey")))) {
				throw new ServiceException("接口校验失败，请联系管理员！");
			}
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = spellListSqlForFDS(paraMap);
			int totalCount = this.service.getCount(sqlWhere);
			List<Map<String, Object>> tempList = null;
			if (query.getPageSize() > 0) {
				tempList = this.service.queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord(), "queryFdsMapForPage");
			} else {
				tempList = this.service.queryMapByWhere(sqlWhere, "queryFdsMapByWhere");
			}
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception ex) {
			ex.printStackTrace();
			return ResponseResult.error(ex.getMessage());
		}
	}
	/**
	 * @description: 拼接FDS的SQL
	 * @author houyuhang
	 * @date 2022/12/21
	 * @modify
	 */
	public String spellListSqlForFDS(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		// 查询已审批完成且没有结项的项目
		sql.appendSingle(" enabled = 1 and projectstate in ({0}) ", GpmSystemConst.ProjectOngoingState);
		// 项目名称
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle("and projectname like '%{0}%' ", value);
			}
		}
		// 项目编号
		if (paraMap.containsKey("qry_code")) {
			String value = paraMap.get("qry_code").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle("and projectcode like '{0}%' ", value);
			}
		}
		SessionUserBean userBean = this.querySessionUserBean(ConvertUtil.convertToString(paraMap.get("qry_usercode")));
        ThreadLocalContext.sessionUserBeanThreadLocal.set(userBean);
		// 数据权限控制，如果是系统超管,不控制数据权限
		if (userBean.getUser().getAdminlevel() < 1) {
			String value = userBean.getUser().getCode();
			// 作为项目经理
			sql.appendSingle(" and ((projectmanagercode = '{0}') ", value);
			// 部门拓展信息表权限查询拼接
			MmsDeptExtraSearchSql(sql, paraMap);
			// 省区地市表权限查询拼接
			MmsProvinceMatchSearchSql(sql, paraMap);
			// 数据权限
			String dataPermission = this.service.getDataPermission(TapSystemConst.TapOperationTypeEnum.Select, "", userBean);
			if (!dataPermission.isEmpty()) {
				sql.appendSingle(" or ({0}) ", dataPermission);
			}
			// 相关方
			sql.appendSingle(" or (EXISTS (SELECT  DISTINCT PROJECTCODE FROM GPMPROJECTSTAKEHOLDER STACKHOLDER WHERE STACKHOLDER.USERCODE = '{0}' AND STACKHOLDER.ENABLED = 1 AND STACKHOLDER.PROJECTCODE=GPMPROJECT.PROJECTCODE )) ", value);
			sql.appendSingle(") ");
		}
		return sql.toString();
	}
	/**
	 * @description: 根据用户code获取sessionuserbean信息
	 * @author: houyuhang
	 * @date: 2023年01月04日
	 * @modify:
	 */
	public SessionUserBean querySessionUserBean(String usercode) {
		SecurityUserDetails userDetails = (SecurityUserDetails) userDetailsService.loadUserByUsername(usercode);
		SessionUserBean sessionUserBean = new SessionUserBean();
		sessionUserBean.setUser(userDetails.getUser());
		sessionUserBean.setOrg(userDetails.getOrg());
		sessionUserBean.setWorkOrg(userDetails.getWorkOrg());
		sessionUserBean.setDept(userDetails.getDept());
		sessionUserBean.setWorkDept(userDetails.getWorkDept());
		sessionUserBean.setRoleList(userDetails.getRoleList());
		return sessionUserBean;
	}
}

